package com.tp;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Add extends CustomWindow implements OnClickListener {
	private static final int PICK_IMAGE = 1;
	private static final int CAMERA_REQUEST = 1888;
	static ImageView imageView;
	// static Photo up;
	String path;
	static String filePath;
	static int type_photo; // luu kieu them anh 1 la choose 2 la capture
	static Bitmap bitmap;
	static float lati, longi;
	static String path_capture;
	public static int flag = 0; // kiem tra xem Add. class duoc goi tu class nao
	// trong Note Diary
	EditText address;
	EditText url;
	public static EditText objName;
	static String _name, location;
	static int id_Obj;
	static String _addr;
	static String _url;
	Spinner spinner;
	int image;
	TextView loc;
	TextView type_txt;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		String a[] = { "Khách sạn", "Nhà hàng", "Sự kiện" };
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add);
		this.icon.setImageResource(R.drawable.add);
		this.title.setText("Thêm đối tượng");

		View add_btn = (findViewById(R.id.add_btn));
		add_btn.setOnClickListener(this);
		type_txt = (TextView) findViewById(R.id.add_type_txt);
		imageView = (ImageView) findViewById(R.id.imageView);
		/* up = new Photo(this, imageView); */
		if (bitmap != null) {
			imageView.setImageBitmap(bitmap);
		}
		loc = (TextView) (findViewById(R.id.add_location_txt));
		if (lati != 0 && longi != 0) {
			location = "Location :    " + lati + "," + longi;
		}
		if (location != null) {
			loc.setVisibility(0);
			loc.setText(location);
		}
		View up_photo = findViewById(R.id.up_photo);
		View location = findViewById(R.id.location);
		up_photo.setOnClickListener(this);
		location.setOnClickListener(this);
		spinner = (Spinner) findViewById(R.id.add_type);
		// Create an ArrayAdapter using the string array and a default spinner
		// layout
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, a);
		// Specify the layout to use when the list of choices appears
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// Apply the adapter to the spinner
		if (flag == 0)
			spinner.setAdapter(adapter);
		else {

			type_txt.setVisibility(View.GONE);
			spinner.setVisibility(View.GONE);
		}
		objName = (EditText) findViewById(R.id.add_name);
		if (_name != null)
			objName.setText(_name);
		if (flag == 1)
			objName.setFocusable(false);
		/*
		 * if(ChooseLocation.name!=null) objName.setText(ChooseLocation.name);
		 */
		address = (EditText) findViewById(R.id.add_addr);
		if (_addr != null)
			address.setText(_addr);
		url = (EditText) findViewById(R.id.add_url);
		if (_url != null)
			url.setText(_url);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_add, menu);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.up_photo:
			_name = objName.getText().toString();
			_addr = address.getText().toString();
			_url = url.getText().toString();
			location = loc.getText().toString();
			String types[] = { "Bộ sưu tập", "Chụp ảnh" };
			String title = "Thêm ảnh";
			DialogCustomize dia = new DialogCustomize();
			dia.a(this, types, title); // display dialog for up_photo type
			// up.upPhoto();
			break;
		case R.id.location:
			/*
			 * Intent cameraIntent = new Intent(
			 * android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			 * startActivityForResult(cameraIntent, CAMERA_REQUEST);
			 */
			_name = objName.getText().toString();
			_addr = address.getText().toString();
			_url = url.getText().toString();
			// image = imageView.ge
			if (imageView.getDrawable() != null)
				bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
			startActivity(new Intent(this, ChooseLocation.class));
			break;
		case R.id.add_btn:
			if (type_photo == 1) // choose photo
				path = savePhotoToServer(filePath);
			else if (type_photo == 2) // capture photo
				path = savePhotoToServer(DialogCustomize.fileName);
			else
				path = "";
			if (flag == 0) {
				if (objName.getText().toString().equals("")
						|| address.getText().toString().equals(""))
					Toast.makeText(this, "Điền đầy đủ các thông tin",
							Toast.LENGTH_SHORT).show();
				else if (path.equals(""))
					Toast.makeText(this, "Chọn ảnh cho đối tượng",
							Toast.LENGTH_SHORT).show();
				else if (loc.getText().toString().equals(""))
					Toast.makeText(this, "Xác định tọa độ cho đối tượng",
							Toast.LENGTH_SHORT).show();
				else
					// add truc tiep tu class Add
					addObject();
				// startActivity(new Intent(this, Main.class));

			} else if (flag == 1) // update tu PostComment
			{
				updateObject();
				// flag =0;
			}
			break;

		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			_name = null;
			_addr = null;
			_url = null;
			lati = 0;
			longi = 0;
			location = null;
			// bitmap = null;
			startActivity(new Intent(this, Main.class));
			return true;
		}
		return false;
	}

	private void updateObject() {
		// TODO Auto-generated method stub
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		
		postParameters.add(new BasicNameValuePair("address", address.getText()
				.toString()));
		postParameters.add(new BasicNameValuePair("url", url.getText()
				.toString()));
		postParameters.add(new BasicNameValuePair("latitude", Float
				.toString(lati)));
		postParameters.add(new BasicNameValuePair("longitude", Float
				.toString(longi)));
		postParameters.add(new BasicNameValuePair("image", path));
		postParameters.add(new BasicNameValuePair("id_User", Integer
				.toString(Constant.user)));
		postParameters.add(new BasicNameValuePair("id_Obj", Integer
				.toString(id_Obj)));

		String result = null;
		try {

			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/ObjectController/updateObject", postParameters);
			String res = result.toString();
			Log.v("ID PHOTO", res);
			// res = res.trim();
			res = res.replaceAll("\\s+", "");
			if (Integer.parseInt(res) > 0) {
				Toast.makeText(this, "Update đối tượng thành công",
						Toast.LENGTH_SHORT).show();
				flag = 0;
				_name = null;
				_addr = null;
				_url = null;
				lati = 0;
				longi = 0;
				location = null;
				bitmap = null;
				startActivity(new Intent(this, PostComment.class));

			} else {
				Toast.makeText(this, "Update đối tượng lỗi",
						Toast.LENGTH_SHORT).show();
			}

		} catch (Exception e) {

		}

	}

	private void addObject() {
		// TODO Auto-generated method stub

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("type", Integer
				.toString(spinner.getSelectedItemPosition() + 1)));
		postParameters.add(new BasicNameValuePair("name", objName.getText()
				.toString()));
		postParameters.add(new BasicNameValuePair("address", address.getText()
				.toString()));
		postParameters.add(new BasicNameValuePair("url", url.getText()
				.toString()));
		postParameters.add(new BasicNameValuePair("latitude", Float
				.toString(lati)));
		postParameters.add(new BasicNameValuePair("longitude", Float
				.toString(longi)));
		postParameters.add(new BasicNameValuePair("image", path));
		postParameters.add(new BasicNameValuePair("id_User", Integer
				.toString(Constant.user)));

		String result = null;
		try {

			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/ObjectController/addObject", postParameters);
			String res = result.toString();
			Log.v("ID PHOTO", res);
			// res = res.trim();
			res = res.replaceAll("\\s+", "");
			if (Integer.parseInt(res) > 0) {
				Toast.makeText(this, "Add object successful",
						Toast.LENGTH_SHORT).show();
				_name = null;
				_addr = null;
				_url = null;
				lati = 0;
				longi = 0;
				location = null;
				bitmap = null;
				startActivity(new Intent(this, Main.class));

			} else {
				Toast.makeText(this, "Add object fail", Toast.LENGTH_SHORT)
						.show();
			}

		} catch (Exception e) {
			objName.setText(e.toString());
			Log.v("Network", e.toString());
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		int rotate = 0;
		switch (requestCode) {
		case CAMERA_REQUEST: // capture photo
			if (resultCode == RESULT_OK) {
				Log.v("CAPTURE", "OK");
				String[] paths = { "/mnt/sdcard/DCIM/Camera" };
				String[] mediaType = { "image/jpeg" };
				MediaScannerConnection.scanFile(this, paths, mediaType, null);
				sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
						Uri.parse("file://"
								+ Environment.getExternalStorageDirectory())));

				ExifInterface exif;
				try {
					exif = new ExifInterface(DialogCustomize.fileName);

					int orientation = exif.getAttributeInt(
							ExifInterface.TAG_ORIENTATION,
							ExifInterface.ORIENTATION_NORMAL);

					switch (orientation) {
					case ExifInterface.ORIENTATION_ROTATE_270:
						rotate = 270;

						break;
					case ExifInterface.ORIENTATION_ROTATE_180:
						rotate = 0;

						break;
					case ExifInterface.ORIENTATION_ROTATE_90:
						rotate = 90;

						break;
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				File photos = new File(DialogCustomize.fileName);
				Log.v("imageFilePath", DialogCustomize.fileName);
				Matrix matrix = new Matrix();
				matrix.postRotate(rotate);
				Bitmap b = decodeFile(photos);
				b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(),
						matrix, true);
				imageView.setImageBitmap(b);
				/*
				 * ContentResolver cr = getContentResolver(); String[] p1 = new
				 * String[] { MediaStore.Images.ImageColumns._ID,
				 * MediaStore.Images.ImageColumns.DATE_TAKEN }; Cursor c1 =
				 * cr.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1,
				 * null, null, p1[1] + " DESC"); if (c1.moveToFirst()) { String
				 * uristringpic = "content://media/external/images/media/" +
				 * c1.getInt(0); Uri newuri = Uri.parse(uristringpic);
				 * Log.i("newuri", "" + newuri);
				 * 
				 * Cursor cursor = cr.query(newuri, new String[] {
				 * MediaColumns.DATA }, null, null, null); cursor.moveToFirst();
				 * 
				 * // Link to the image String imageFilePath =
				 * cursor.getString(0); File photos = new File(imageFilePath);
				 * Log.v("imageFilePath", imageFilePath); Bitmap b =
				 * decodeFile(photos); b = Bitmap.createScaledBitmap(b, 150,
				 * 150, true); // ImageView imageView = (ImageView) //
				 * findViewById(R.id.select_image); imageView.setImageBitmap(b);
				 * cursor.close();
				 * 
				 * } c1.close();
				 */

			} else
				Log.v("CAPTURE", "FAIL");
			break;
		case PICK_IMAGE: // choose from sdcard

			/* up.pickImage(requestCode, resultCode, data); */
			if (resultCode == Activity.RESULT_OK) {

				Uri _uri = data.getData();
				Log.v("uri", _uri.toString());
				if (_uri != null) {
					// User had pick an image.
					Cursor cursor = this.getContentResolver().query(_uri,
							new String[] { MediaColumns.DATA }, null, null,
							null);
					cursor.moveToFirst();

					// Link to the image
					String imageFilePath = cursor.getString(0);
					Log.v("imageFilePath", imageFilePath);
					filePath = imageFilePath;
					Log.v("filePath", filePath);
					File photos = new File(imageFilePath);
					Bitmap b = decodeFile(photos);
					b = Bitmap.createScaledBitmap(b, 150, 150, true);
					imageView.setImageBitmap(b);
					cursor.close();
				}
			}

			break;

		default:
		}

	}

	static Bitmap decodeFile(File f) {

		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 700;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale++;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;

	}

	public String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaColumns.DATA };
			Cursor cursor = managedQuery(contentUri, proj, null, null, null);
			int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

	public String savePhotoToServer(String pathToOurFile) {
		HttpURLConnection connection = null;
		DataOutputStream outputStream = null;
		// DataInputStream inputStream = null;

		// String pathToOurFile = "/data/file_to_send.mp3";
		String urlServer = Constant.host + "/PhotoController/savePhoto";
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		String result = null;
		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1 * 1024 * 1024;

		try {
			FileInputStream fileInputStream = new FileInputStream(new File(
					pathToOurFile));

			URL url = new URL(urlServer);
			connection = (HttpURLConnection) url.openConnection();

			// Allow Inputs & Outputs
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);

			// Enable POST method
			connection.setRequestMethod("POST");

			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);

			outputStream = new DataOutputStream(connection.getOutputStream());
			outputStream.writeBytes(twoHyphens + boundary + lineEnd);
			outputStream
					.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
							+ pathToOurFile + "\"" + lineEnd);
			outputStream.writeBytes(lineEnd);
			bytesAvailable = fileInputStream.available();
			bufferSize = Math.min(bytesAvailable, maxBufferSize);
			buffer = new byte[bufferSize];

			// Read file
			bytesRead = fileInputStream.read(buffer, 0, bufferSize);

			while (bytesRead > 0) {
				outputStream.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}

			outputStream.writeBytes(lineEnd);
			outputStream.writeBytes(twoHyphens + boundary + twoHyphens
					+ lineEnd);

			// Responses from the server (code and message)
			int serverResponseCode = connection.getResponseCode();
			if (serverResponseCode == 200) {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				br.close();
				result = sb.toString();

			}
			// String serverResponseMessage = connection.getResponseMessage();
			Log.v("SYSTEM", result);
			fileInputStream.close();
			outputStream.flush();
			outputStream.close();

		} catch (Exception ex) {
			// Exception handling
		}
		return result;
	}

}
